<template>
  <div class="costPlan-container">
    <a-row :gutter="18">
      <a-col :span="16">
        <!-- 查询区域 -->
        <a-form layout="inline" class="j-inline-form">
          <!-- 固定条件 -->
          <a-form-item :label="queryConfig[0].label">
            <j-search-select-tag v-if="queryConfig[0].dictCode" v-model="queryParam[queryConfig[0].key]" :placeholder="'请输入' + (queryConfig[0].label)" :dict="queryConfig[0].dictCode" @change="searchQuery" style="width:180px;" :getPopupContainer="null"/>
            <a-input v-else v-model="queryParam[queryConfig[0].key]" :placeholder="'请输入' + (queryConfig[0].label)" @pressEnter="searchQuery"/>
          </a-form-item>
          <!-- 动态生成的查询条件 -->
          <j-select-biz-query-item v-if="queryConfig.length>1" v-show="showMoreQueryItems" :queryParam="queryParam" :queryConfig="queryConfig.slice(1)" :search="true" @pressEnter="searchQuery"/>
          <!-- 按钮 -->
          <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
          <a-button type="primary" @click="searchReset_" icon="reload" style="margin-left: 8px">重置</a-button>
          <a v-if="queryConfig.length>1" @click="showMoreQueryItems=!showMoreQueryItems" style="margin-left: 8px">
            {{ showMoreQueryItems ? '收起' : '展开' }}
            <a-icon :type="showMoreQueryItems ? 'up' : 'down'"/>
          </a>
        </a-form>
        <a-table
          size="middle"
          bordered
          :rowKey="rowKey"
          :columns="innerColumns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{ y: 240 }"
          :rowSelection="{selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox':'radio'}"
          @change="handleTableChange">
        </a-table>
      </a-col>
      <a-col :span="8">
        <a-card :title="'已选' + queryConfig[0].label" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">
          <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable">
              <span slot="action" slot-scope="text, record, index">
                <a @click="handleDeleteSelected(record, index)">删除</a>
              </span>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
  import Ellipsis from '@/components/Ellipsis'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { cloneObject } from '@/utils/util'
  import JSelectBizQueryItem from '@/components/jeecgbiz/JSelectBizComponent/JSelectBizQueryItem.js'
   import { getAction } from '@/api/manage'

  export default {
    name: 'costPlan',
    mixins: [JeecgListMixin],
    components: {Ellipsis, JSelectBizQueryItem},
    props: {
      value: {
        type: String,
        default: ''
      },
      multiple: {
        type: Boolean,
        default: true
      },
      listUrl: {
        type: String,
        required: true,
        default: ''
      },
      columns: {
        type: Array,
        required: true,
        default: () => []
      },
      // 查询配置
      queryConfig: {
        type: Array,
        default: () => []
      },
      //增加默认查询参数
      queryParamConfig: {
        type: Object,
        default: () => { }
      },
      rowKey: {
        type: String,
        default: 'id'
      },
      valueKey: {
        type: String,
        default: 'ids'
      },
      // 过长裁剪长度，设置为 -1 代表不裁剪
      ellipsisLength: {
        type: Number,
        default: 12
      },
      //右侧已选中项展示
      modalPropsCustom: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 已选择列表
        selectedTable: {
          pagination: false,
          scroll: { y: 240 },
          columns: 
          this.modalPropsCustom ? 
            [...this.columns.filter(item => item.isShow).map(item => {
                return {
                  ...item,
                  width: item.width
                }
              }),
              { title: '操作', dataIndex: 'action', align: 'center', width: 60, scopedSlots: { customRender: 'action' }, }
            ] : 
            [
              {
                ...this.columns[0],
                width: this.columns[0].width,
              },
              { title: '操作', dataIndex: 'action', align: 'center', width: 60, scopedSlots: { customRender: 'action' }, }
            ],
          dataSource: [],
        },
        renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),
        url: { list: this.listUrl },
        queryParam: {...this.queryParamConfig},
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        showMoreQueryItems: false,
        oriDataSource: [],
        deleteEvent: false
      }
    },
    computed: {
      // 表头
      innerColumns() {
        let columns = cloneObject(this.columns)
        columns.forEach(column => {
          // 给所有的列加上过长裁剪
          if (this.ellipsisLength !== -1) {
            column.customRender = (text) => this.renderEllipsis(text)
          }
        })
        return columns
      }
    },
    watch: {
      dataSource: {
        handler(val){
          //处理数据
          let that = this;
          function handleValue(){
            let value = (that.value && that.value.split(',')) || [];
            // 只有初始化阶段赋值
            if(that.ipagination.current === 1 && !that.deleteEvent){
              that.selectedRowKeys = value;
            }
          }       
          if(that.value){
            handleValue();
          }else{
            setTimeout(() => {
              handleValue();
            }, 100)
          }         
        }
      },
      selectedRowKeys: {
        handler(val){
          // 只有初始化阶段请求
          if(this.ipagination.current === 1 && !this.deleteEvent){
            this.getInitSelectedTable();
            return;
          }
          if(!(val && val.length)){
            this.selectedTable.dataSource = [];
            this.oriDataSource = [];
            return;
          }
          this.oriDataSource = [...this.oriDataSource, ...this.dataSource];
          //去重
          let map = new Map();
          for (let item of this.oriDataSource) {
            if (!map.has(item.id)) {
              map.set(item.id, item);
            };
          };
          this.oriDataSource = [...map.values()];
          this.selectedTable.dataSource = this.oriDataSource.filter(item => {
            return val.indexOf(item[this.rowKey]) > -1;
          })
        }
      }
    },
    methods: {
      /** 删除已选择的 */
      handleDeleteSelected(record, index) {
        //删除事件存在
        this.deleteEvent = true;
        this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
        //修改表单值
        this.$emit('change', this.selectedRowKeys.join(','))
      },

      searchReset_(){
        this.queryParam = {...this.queryParamConfig};
        this.loadData(1);
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        //新增、删除事件存在
        this.deleteEvent = true;
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        //修改表单值
        this.$emit('change', this.selectedRowKeys.join(','))
      },
      getInitSelectedTable() {
        if(!this.value){
          this.selectedTable.dataSource = [];
          this.oriDataSource = [];
          return;
        }
        getAction(this.listUrl, {
          // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
          [this.valueKey]: this.value,
          pageNo: 1,
          pageSize: this.value.split(',').length
        }).then((res) => {
          if (res.success) {
            this.selectedTable.dataSource = (res.result && res.result.records) || [];
            this.oriDataSource = (res.result && res.result.records) || [];
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style lang="less" scoped>
  .costPlan-container{
    margin-top: 10px;
  }
  
  .j-inline-form {
    /deep/ .ant-form-item {
      margin-bottom: 12px;
    }

    /deep/ .ant-form-item-label {
      line-height: 32px;
      width: auto;
    }

    /deep/ .ant-form-item-control {
      height: 32px;
      line-height: 32px;
    }
  }
</style>